import { Form } from '@formily/core';
import { onFieldChange, onFieldValueChange } from "@formily/core";
import moment from "moment";
import { uuidv4 } from "@ey-utils/utils";
import { plus, minus } from "@ey-utils/utils/numberPrecision";

const onReturn = (value: string) => value === "AST02";

/**
 * 报账明细
 * @param cb
 */
export const onAcctItemsChange = (cb: any) => {
  onFieldValueChange("acctItems.*.payer", (field: any, form: any) => {
    const { modified } = field || {};
    if (modified) {
      console.log("报账明细(acctItems.payer组织)变更", modified, field);
      cb?.();
    }
  });
  onFieldValueChange("acctItems.*.ieAmt", (field: any, form: any) => {
    const { modified } = field || {};
    if (modified) {
      console.log("报账明细(acctItems.ieAmt金额)变更", modified, field);
      cb?.();
    }
  });
};

/**
 * 归还规则字段变更
 * startMonth 起始归还月份
 * endMonth 最终归还月份
 * AST01 分次归还
 * AST02 一次归还
 * 归还规则=一次归还时，最终归还月份默认为起始归还月份，不可修改
 */

export const onSpltTypeChange = (cb: any) => {
  onFieldChange("spltType", (field: any, form: any) => {
    const { modified, value } = field || {};
    if (modified) {
      console.log("规划规则(spltType)变更", modified, field);
      const oneReturn = onReturn(value);
      if (oneReturn) {
        form.setValuesIn("endMonth", form.getValuesIn("startMonth"));
      }
      form.setFieldState("endMonth", (state: any) => {
        state.componentProps.disabled = oneReturn;
      });
      cb?.();
    }
  });
};

/**
 * 设置起始归还月份
 */
export const onStartMonth = (cb: any) => {
  onFieldChange("startMonth", (field: any, form: any) => {
    const { modified } = field || {};
    if (modified) {
      console.log("起始归还月份(startMonth)变更", modified, field);
      const oneReturn = onReturn(form.getValuesIn("spltType"));
      if (oneReturn) {
        form.setValuesIn("endMonth", form.getValuesIn("startMonth"));
      }
      cb?.();
    }
  });
};

/**
 * 设置起始归还月份
 */
export const onEndMonthChange = (cb: any) => {
  onFieldChange("endMonth", (field: any, form: any) => {
    const { modified } = field || {};
    if (modified) {
      console.log("最终归还月份(endMonth)变更", modified, field);
      cb?.();
    }
  });
};

//获取两日期之间日期列表函数
export const getDifflist = (
  startTime: string,
  endTime: string,
  type: "day" | "month" | "year"
) => {
  const dateArray = []; // dateArray 起止日期中间的所有日期列表
  let currentDate = moment(startTime); // 起止日期
  const stopDate = moment(endTime); // 截止日期
  // 开始日期小于等于结束日期,并循环
  while (currentDate <= stopDate) {
    if (type === "day")
      dateArray.push(moment(currentDate).format("YYYY-MM-DD")); // 两个日期间的所有日期
    if (type === "month") dateArray.push(moment(currentDate).format("YYYY-MM")); // 两个月份间的所有月份
    if (type === "year") dateArray.push(moment(currentDate).format("YYYY")); // 两个年份间的所有年份
    currentDate = moment(currentDate).add(1, type); // 根据类型+1
  }
  return dateArray;
};
/**
 * 创建items
 */
export const createItems = (diffMonth: any[] = [], acctItems: any[] = [], batch = false, form: Form) => {
  const spltItems: any[] = [];
  if (batch) {
    acctItems.forEach((acct: any) => {
      const group: any = [];
      const { payer, payerName, ieAmt } = acct || {};
      console.log(acct, 'acct')
      diffMonth.forEach((month: string, monthIndex: number) => {
        // 组织存在 在分组
        if (payer) {
          group.push({
            id: uuidv4(),
            disabled: monthIndex === 0,
            plnMonth: month,
            payer,
            payerName,
            claimAmt: monthIndex === 0 ? ieAmt : "",
          });
        }
      });
      spltItems.push(...group);
    });
  } else {
    diffMonth.forEach((month: string, monthIndex: number) => {
      // 单个预付款申请
      spltItems.push({
        id: uuidv4(),
        disabled: monthIndex === 0,
        plnMonth: month,
        claimAmt: monthIndex === 0 ? form?.getValuesIn('claimAmt') || 0 : '',
      });
    });
  }

  return spltItems;
};

// 设置表格状态
export const setTableState = (form: any, spltItems: any = []) => {
  form.setFieldState(`spltItems.*.claimAmt`, (field: any) => {
    const index = field.index;
    const item = spltItems[index];

    field.componentProps = {
      ...field.componentProps,
      editable: !item?.disabled,
      disabled: !!item?.disabled,
    };
  });
};

// 设置倒减金额
export const onSpltItemsClaimAmtChange = (batch: boolean) => {
  onFieldChange("spltItems.*.claimAmt", (field: any, form: any) => {
    const { claimAmt, spltItems, acctItems } = form.values;
    const { modified, index } = field || {};

    if (modified && !spltItems[index]?.disabled) {
      if (batch) {
        // 批量
        acctItems.forEach((item: any) => {
          const { ieAmt, payer } = item || {}; // 当前组织的付款金额
          const total = spltItems.reduce((t: number, cur: any) => {
            if (cur.disabled || cur.payer !== payer) {
              return t;
            }
            return plus(t, cur.claimAmt || 0);
          }, 0);

          const index = spltItems.findIndex(
            (cur: any) => cur.disabled && cur.payer === payer
          );

          form.setValuesIn(
            `spltItems.${index}.claimAmt`,
            minus(ieAmt || 0, total)
          );
        });
      } else {
        const total = spltItems.reduce((t: number, cur: any) => {
          if (cur.disabled) {
            return t;
          }
          return plus(t, cur.claimAmt || 0);
        }, 0);

        form.setValuesIn("spltItems.0.claimAmt", minus(claimAmt || 0, total));
      }
    }
  });
};

// 申请金额发生变化
export const onclaimAmtChange = (cb: any) => {
  onFieldChange("claimAmt", (field: any, form: any) => {
    const { modified } = field || {};
    if (modified) {
      console.log("申请金额(claimAmt)变更", modified, field);
      cb?.();
    }
  });
};
